package com.ffspace.blog.service;


import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import com.auth0.jwt.pem.PemReader;
import com.ff.blog.common.BaseResult;
import com.ff.blog.common.CommonTool;
import com.ff.blog.enums.UserStatus;
import com.ff.blog.util.SendEmail;
import com.ffspace.blog.core.dal.dataobject.User;
import com.ffspace.blog.core.dal.mapper.UserMapper;

public class UserServiceImpl implements UserService{

	private static Logger	logger = LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Autowired
	private UserMapper userMapper;

	private String sendEmail;

	private String emailPwd;

	private String smtpUrl;

	private String baseUrl;

    private String   pubKeyFile;

    private String   privFile;
	
	@Transactional
	public void register(User user) {
		try
		{
			Date now = new Date();
			user.setStatus(UserStatus.UNACTIVE.getCode());
			user.setCreateTime(now);
			user.setUpdateTime(now);
			userMapper.insert(user);
			User newUser = userMapper.selectByLoginName(user.getLoginName());
			PrivateKey signKey = PemReader.readPrivateKey(getPrivFile());
			String token = CommonTool.generateToken(newUser.getId(), signKey);
			String activeUrl = baseUrl + "/active.htm?token=" + token;
			sendTradeCollFileEmail(user.getEmail(), null, activeUrl);
		}
		catch (Exception e)
		{
			logger.error("register error", e);
			throw new RuntimeException(e);
		}
		
	}

	public BaseResult<User> login(String loginName, String password) {
		BaseResult<User> result = new BaseResult<User>();
		try
		{
			User user = userMapper.selectByLoginName(loginName);
			if (null == user)
			{
				result.setSuccess(false);
				result.setMessage("用户不存在");
				return result;
			}
			
			if (!user.getPassword().equals(password))
			{
				result.setSuccess(false);
				result.setMessage("密码错误");
				return result;
			}
			
			result.setSuccess(true);
			result.setMessage("登录成功");
	
		}
		catch (Exception e)
		{
			logger.error("login error", e);
			result.setSuccess(false);
			result.setMessage("服务端错误");
		}
		return result;
	}
	
	private void sendTradeCollFileEmail(String tgtEmail,String file, String url){
		SendEmail.send(tgtEmail, getSendEmail(), getSmtpUrl(), getEmailPwd(), "账号激活邮件",
				"点击以下链接激活账户: \r\n\r\n \t "+url+"  "+"\r\n\r\n\r\n\r\n本邮件由系统自动发出, 请勿回复",
				file, file);
	}

	public String getSendEmail() {
		return sendEmail;
	}

	public void setSendEmail(String sendEmail) {
		this.sendEmail = sendEmail;
	}

	public String getEmailPwd() {
		return emailPwd;
	}

	public void setEmailPwd(String emailPwd) {
		this.emailPwd = emailPwd;
	}

	public String getSmtpUrl() {
		return smtpUrl;
	}

	public void setSmtpUrl(String smtpUrl) {
		this.smtpUrl = smtpUrl;
	}

	public BaseResult<String> active(String token) {
		BaseResult<String> result = new BaseResult<String>();
		try
		{
			PublicKey signKey = PemReader.readPublicKey(getPubKeyFile());
			Map<String, Object> claims = CommonTool.parseToken(token, signKey);
			if (null == claims || null == claims.get("mid"))
			{
				result.setSuccess(false);
				result.setMessage("该链接已失效");
				return result;
			}
			Integer userId = (Integer)claims.get("mid");
			User record = new User();
			record.setId(userId);
			record.setStatus(UserStatus.ACTIVED.getCode());
			int count = userMapper.updateByPrimaryKeySelective(record);
			if (count <= 0)
			{
				result.setSuccess(false);
				result.setMessage("该账号不存在");
				return result;
			}
			result.setSuccess(true);
			result.setMessage("激活成功");
		}
		catch (Exception e)
		{
			logger.error("active error", e);
			result.setSuccess(false);
			result.setMessage("服务器错误");
		}
		return result;
	}
	
	public String getPubKeyFile()
	{
		return this.pubKeyFile;
	}

	public String getPrivFile()
	{
		return this.privFile;
	}

	public String getBaseUrl() {
		return baseUrl;
	}

	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	public void setPubKeyFile(String pubKeyFile) {
		this.pubKeyFile = pubKeyFile;
	}

	public void setPrivFile(String privFile) {
		this.privFile = privFile;
	}
	
	
}
